<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8"/>
    <title>组卷工具</title>
    <link rel="stylesheet" href="index.css"/>
    <link rel="stylesheet" href="style.css"/>
</head>
<body>

<h1 style="display: flex; justify-content: space-between; align-items: center;">
    <span>考题列表</span>
    <a href="history.html" class="history-link">历史组卷 &gt;</a>
</h1>

<!-- 顶部 -->
<div class="pagination">
    <button onclick="loadFirst()">首页</button>
    <button onclick="loadPrev()">上一页</button>
    每页数量：
    <select id="limitSelectTop" onchange="changeLimit(this)">
        <option value="5">5</option>
        <option value="10" selected>10</option>
        <option value="20">20</option>
    </select>
    <span id="pageInfoTop">加载中...</span>
    <button onclick="loadNext()">下一页</button>
    <button onclick="loadLast()">尾页</button>
    <button class="viewSelectedBtn" onclick="confirmSelection()">
        查看已选考题
        <span class="selectedCountBadge">0</span>
    </button>
    <button onclick="clearSelection()">清除勾选</button>
</div>
<div class="filter-bar">
    <label>题型：
        <select id="filterType"></select>
    </label>
    <label>难度（正确率）：
        <select id="filterRating"></select>
    </label>
</div>
<div class="random-select-bar">
    随机：
    <button onclick="randomSelect(1)">+1</button>
    <button onclick="randomSelect(5)">+5</button>
    <button onclick="randomSelect(10)">+10</button>
</div>

<!-- 考题列表 -->
<ul id="quesList"></ul>

<!-- 底部 -->
<div class="pagination">
    <button onclick="loadFirst()">首页</button>
    <button onclick="loadPrev()">上一页</button>
    每页数量：
    <select id="limitSelectBottom" onchange="changeLimit(this)">
        <option value="5">5</option>
        <option value="10" selected>10</option>
        <option value="20">20</option>
    </select>
    <span id="pageInfoBottom">加载中...</span>
    <button onclick="loadNext()">下一页</button>
    <button onclick="loadLast()">尾页</button>
    <button class="viewSelectedBtn" onclick="confirmSelection()">
        查看已选考题
        <span class="selectedCountBadge">0</span>
    </button>
    <button onclick="clearSelection()">清除勾选</button>
</div>

<script>
    let page = 1;
    let limit = 10; // 初始每页数量
    let total = 0;
    let selectedQuesIds = new Set();
    let selectedFetched = false;

    // 初始化已勾选题目
    async function initSelectedIdsOnce() {
        if (!selectedFetched) {
            const serverSelectedIds = await window.ipcRender.invoke('ques:getSelectedIds');
            selectedQuesIds = new Set(serverSelectedIds);
            selectedFetched = true;
            updateSelectedCountBadge();
        }
    }

    // 载入题型信息
    async function loadQuesTypes() {
        const typeSelect = document.getElementById('filterType');
        const previousValue = typeSelect.value;

        const ratingFilter = document.getElementById('filterRating').value;
        const types = await window.ipcRender.invoke('db:getQuesTypes', {rating: ratingFilter});
        typeSelect.innerHTML = '';

        const allOption = document.createElement('option');
        allOption.value = '';
        allOption.textContent = '全部';
        typeSelect.appendChild(allOption);

        // 动态添加题型
        types.forEach(t => {
            const option = document.createElement('option');
            option.value = t.type;
            option.textContent = `${t.type}（${t.count}）`;
            typeSelect.appendChild(option);
        });

        const match = Array.from(typeSelect.options).some(opt => opt.value === previousValue);
        typeSelect.value = match ? previousValue : '';
    }

    // 载入难度信息
    async function loadRatingRanges() {
        const ratingSelect = document.getElementById('filterRating');
        const previousValue = ratingSelect.value;

        const typeSelect = document.getElementById('filterType');
        const selectedType = typeSelect.value;
        const ranges = await window.ipcRender.invoke('db:getQuesRatingRanges', {type: selectedType});

        ratingSelect.innerHTML = '';
        const allOption = document.createElement('option');
        allOption.value = '';
        allOption.textContent = '全部';
        ratingSelect.appendChild(allOption);

        ranges.forEach(r => {
            const option = document.createElement('option');
            option.value = r.difficulty;
            option.textContent = `${r.difficulty}（${r.count}）`;
            ratingSelect.appendChild(option);
        });

        const hasPrevious = Array.from(ratingSelect.options).some(opt => opt.value === previousValue);
        if (hasPrevious) {
            ratingSelect.value = previousValue;
        } else {
            ratingSelect.value = ''; // 没有匹配项则退回默认“全部”
        }
    }

    // 加载考题列表
    async function loadQuesList() {
        const offset = (page - 1) * limit;
        const type = document.getElementById('filterType').value;
        const rating = document.getElementById('filterRating').value;

        const quesList = await window.ipcRender.invoke('db:getQuesList', {limit, offset, type, rating});
        total = await window.ipcRender.invoke('db:getQuesCount', {type, rating});

        const ul = document.getElementById('quesList');
        ul.innerHTML = '';

        quesList.forEach(q => {
            const li = document.createElement('li');
            li.className = 'collapsed';

            // 自定义checkbox
            const label = document.createElement('label');
            label.className = 'custom-checkbox-wrapper';
            label.setAttribute('for', `checkbox-${q.id}`); // 为 label 设置 for 属性，绑定到 input
            // 真勾选框（隐藏）
            const checkbox = document.createElement('input');
            checkbox.type = 'checkbox';
            checkbox.id = `checkbox-${q.id}`; // 为每个 input 设置唯一的 id
            checkbox.checked = selectedQuesIds.has(q.id);
            checkbox.className = 'custom-checkbox';
            // 假勾选框
            const fakeBox = document.createElement('span');
            fakeBox.className = 'fake-checkbox';

            // 题干部分
            const paper = document.createElement('span');
            paper.className = 'paper-name';
            paper.textContent = q.paper_name;
            const type = document.createElement('span');
            type.className = 'ques-type';
            type.textContent = q.ques_type;
            const text = document.createElement('span');
            text.className = 'ques-text';
            text.textContent = q.content;

            const content = document.createElement('span');
            content.className = 'ques-content';
            content.appendChild(type);
            content.appendChild(paper);
            content.appendChild(text);

            // 绑定事件
            checkbox.onchange = () => {
                if (checkbox.checked) {
                    selectedQuesIds.add(q.id);
                    li.classList.add('selected');
                } else {
                    selectedQuesIds.delete(q.id);
                    li.classList.remove('selected');
                }
                updateSelectedCountBadge()
            };
            content.onclick = () => {
                li.classList.toggle('collapsed');
                li.classList.toggle('expanded');
            };

            label.appendChild(checkbox);
            label.appendChild(fakeBox);

            const wrapper = document.createElement('div');
            wrapper.className = 'item-wrapper';
            wrapper.appendChild(label);
            wrapper.appendChild(content);

            li.appendChild(wrapper);
            ul.appendChild(li);

        });

        const totalPages = Math.max(1, Math.ceil(total / limit));
        const pageText = `第 ${page} 页 / 共 ${totalPages} 页`;

        document.getElementById('pageInfoTop').textContent = pageText;
        document.getElementById('pageInfoBottom').textContent = pageText;
        document.getElementById('limitSelectTop').value = limit;
        document.getElementById('limitSelectBottom').value = limit;
    }

    // 随机选择
    async function randomSelect(count) {
        const type = document.getElementById('filterType').value;
        const rating = document.getElementById('filterRating').value;

        const alreadySelected = Array.from(selectedQuesIds);

        // 请求主进程获取随机题目
        const newIds = await window.ipcRender.invoke('db:getRandomIdList', {
            count,
            type,
            rating,
            exclude: alreadySelected,
        });
        console.log(newIds);

        if (!newIds || newIds.length === 0) return; // 没有符合条件的
        newIds.forEach(id => selectedQuesIds.add(id));

        // 刷新勾选状态
        updateSelectedCountBadge();
        await loadQuesList();
    }

    function loadFirst() {
        page = 1;
        loadQuesList();
    }

    function loadLast() {
        const totalPages = Math.ceil(total / limit);
        page = totalPages;
        loadQuesList();
    }

    function loadPrev() {
        if (page > 1) {
            page--;
            loadQuesList();
        }
    }

    function loadNext() {
        const totalPages = Math.ceil(total / limit);
        if (page < totalPages) {
            page++;
            loadQuesList();
        }
    }

    function changeLimit(selectElem) {
        limit = parseInt(selectElem.value);
        page = 1;
        loadQuesList();
    }

    function confirmSelection() {
        const ids = Array.from(selectedQuesIds);
        const type = document.getElementById('filterType').value;
        const rating = document.getElementById('filterRating').value;
        if (ids.length === 0) {
            alert('请先选择至少一道题');
            return;
        }
        window.ipcRender.send('ques:confirmSelected', {ids, type, rating});
        window.location.href = 'selected.html';
    }

    function clearSelection() {
        selectedQuesIds.clear();
        document.querySelectorAll('.item-wrapper input[type="checkbox"]').forEach(cb => {
            cb.checked = false;
        });
        updateSelectedCountBadge();
    }

    function updateSelectedCountBadge() {
        const badges = document.querySelectorAll('.selectedCountBadge');
        const count = selectedQuesIds.size;

        badges.forEach(badge => {
            if (count === 0) {
                badge.style.display = 'none';
            } else {
                badge.style.display = 'inline-block';
                badge.textContent = count;
            }
        });
    }

    // 初始化
    window.addEventListener('DOMContentLoaded', async () => {
        // 获取已选择的id列表
        await initSelectedIdsOnce();

        // 获取已选择的筛选条件
        const saved = await window.ipcRender.invoke('filter:get');
        const savedType = saved.type || '';
        const savedRating = saved.rating || '';
        // 加载筛选框内容
        await loadQuesTypes();
        await loadRatingRanges();
        // 恢复筛选条件
        document.getElementById('filterType').value = savedType;
        document.getElementById('filterRating').value = savedRating;
        await loadQuesTypes();
        await loadRatingRanges();

        await loadQuesList();

        document.getElementById('filterType').addEventListener('change', () => {
            page = 1;
            loadRatingRanges();
            loadQuesList();
        });
        document.getElementById('filterRating').addEventListener('change', () => {
            page = 1;
            loadQuesTypes();
            loadQuesList();
        });
    })
</script>
</body>

